﻿#include <chrono>

#include "Demo/SystemTime.h"
           
namespace Algorithm {

uint64_t SystemTime::systemTime_ = 0U;
uint64_t SystemTime::systemTimeK1_ = 0U;
float SystemTime::cycleTime_ = 0.05F;

#ifdef SIM_TIMESTAMP_INJECT 
static uint64_t timeStampSim = 0U;
void set_timeStampSim(const uint64_t timeStamp) {timeStampSim = timeStamp;};
#else
void set_timeStampSim(const uint64_t timeStamp){}
#endif

void SystemTime::updateSystemTime(void)
{
	systemTime_ = timeStamp();
	if (0U == systemTimeK1_)
	{
		cycleTime_ = 0.05F;
	}
	else
	{
		if(systemTime_ > systemTimeK1_)
		{
			cycleTime_ = static_cast<float>(systemTime_ - systemTimeK1_)/1000.0F;
		}
		else
		{
			cycleTime_ = 0.05F;
		}
	}
	systemTimeK1_ = systemTime_;
}

uint64_t SystemTime::timeStamp(void)
{
#ifdef SIM_TIMESTAMP_INJECT 
	return (timeStampSim + 1000000/2)/1000000; //对应仿真数据时间戳
#else
	return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count()); // 实车环境使用底层提供的时间戳函数
#endif
}

uint64_t SystemTime::timeStampNs(void)
{
#ifdef SIM_TIMESTAMP_INJECT 
	return timeStampSim;
#else
	return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
#endif
}

} // namespace Algorithm